package com.sctvcloud.renhe.ui.activities;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.db.DBUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.FSubscribe;
import com.sctvcloud.renhe.http.AbsListNetCallback;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.adapter.MySubscribeAdapter;
import com.sctvcloud.renhe.ui.dialog.CheckPermission;
import com.sctvcloud.renhe.ui.dialog.ShowDiaFragment;
import com.sctvcloud.renhe.ui.fragment.ColumnBaseFragment;
import com.sctvcloud.renhe.ui.util.RBaseItemDecoration;
import com.sctvcloud.renhe.ui.utils.NotificationsUtils;
import com.sctvcloud.renhe.ui.utils.TitleUtils;
import com.sctvcloud.renhe.utils.ListTypeUtils;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的预约
 */
public class MySubscribeActivity extends BaseActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.my_subscribe_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView subscribe_rv;
    @BindView(R.id.title_top_back)
    protected ImageView back;
    @BindView(R.id.my_subscribe_no)
    protected LinearLayout no_subscribe;
    private MySubscribeAdapter adapter;
    private LinearLayoutManager manager;
    private String month, day, hour, minute;
    private int type;
    private List<FSubscribe> subscribeList;
    private String RECEIVE_TAG = "com.sctvcloud.renhe.NOTIFICATION";
    private ArrayList<FSubscribe> aSubscribeList;
    private int currentPage = 0;
    private int pageAll;
    private ArrayList<FSubscribe> readySubscribe;
    private String url;
    private ShowDiaFragment showDiaFragment;
    public static final String SHOW_TAG = "dia_show_fragment";
    private Calendar calendar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("直播预约");
        initData();
        checkNotificationPermission();

    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_my_subscribe);
        ButterKnife.bind(this);
    }

    private void checkNotificationPermission() {
        boolean isNotification = NotificationsUtils.isNotificationEnabled(this);//NotificationManagerCompat.from(this).areNotificationsEnabled();
        if (!isNotification) {
            showDialog();
        }
        JLog.e("====notifi==" + isNotification);
    }

    private void showDialog() {
        if (showDiaFragment == null) {
            showDiaFragment = new ShowDiaFragment();
        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.setType(2);
        showDiaFragment.show(getSupportFragmentManager(), SHOW_TAG);
    }


    private void initData() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();
        back.setOnClickListener(this);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        subscribe_rv.setLayoutManager(manager);
        subscribe_rv.setItemAnimator(new DefaultItemAnimator());
        subscribe_rv.addItemDecoration(new RBaseItemDecoration(0));
        aSubscribeList = new ArrayList<>();
        readySubscribe = new ArrayList<>();
    }

    private void toSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                , Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, CheckPermission.SETTING_REQUEST);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_back:
                onBackPressed();
                break;
        }

    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {
        if (null != readySubscribe) {
            readySubscribe.clear();
        }
        getSubscribeData();
    }

    /**
     * 设置闹钟定时通知提醒
     */
    private void setAlarm(String id, String title, String url, FSubscribe subscribe) {
        setDates(subscribe);
        int mon = Integer.parseInt(month) - 1;
        int da = Integer.parseInt(day);
        int hou = Integer.parseInt(hour);
        int min = Integer.parseInt(minute);
        final int AdvanceTime = 10;//设置提前十分钟发送消息
        Date dataDate = DateUtils.getDataDate(subscribe);
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        long currentTimes = calendar.getTimeInMillis();
        long c = System.currentTimeMillis();
        if (dataDate != null) {
            long liveTime = dataDate.getTime() - AdvanceTime * 1000 * 60;
            if (currentTimes <= liveTime) {
                //如果减掉十分钟，时间依然比当前时间靠后，那么就减去十分钟定时，否则直接定时为开播时间。
                if (min < AdvanceTime) {
                    min = min + 60 - AdvanceTime;//设置提前十分钟发送消息
                    hou = hou - 1;
                } else {
                    min = min - AdvanceTime;
                }
            }
            liveTime = dataDate.getTime();
            if (currentTimes <= liveTime) {
                calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                calendar.set(Calendar.MONTH, mon);//从0开始，0表是1月，1表示2月依次类推
                calendar.set(Calendar.DAY_OF_MONTH, da);
                calendar.set(Calendar.HOUR_OF_DAY, hou);
                calendar.set(Calendar.MINUTE, min);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                long timeInMillis = calendar.getTimeInMillis();
                Intent intent = new Intent(RECEIVE_TAG);
                intent.putExtra(EX_ID, id);
                intent.putExtra(EX_TITLE, title);
                intent.putExtra(EX_URL, url);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, Integer.parseInt(id), intent, 0);
                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                //   am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1 * 1000, pendingIntent);//重复提醒
                am.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
                subscribe.setSubscribe(!subscribe.isSubscribe());
                adapter.notifyDataSetChanged();
                setSubscribeList(subscribe);
            } else {
                toast(R.string.living_over_time);
            }
        }

    }

    /**
     * 关闭定时通知提醒
     */
    private void stopAlarm(String id, String title, String url) {

        Intent intent = new Intent(RECEIVE_TAG);
        intent.putExtra(EX_ID, id);
        intent.putExtra(EX_TITLE, title);
        intent.putExtra(EX_URL, url);
        PendingIntent pi = PendingIntent.getBroadcast(this, Integer.parseInt(id),
                intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pi);
    }

    /**
     * 获取预约数据
     */
    private void getSubscribeData() {
        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getIntExtra(EX_TYPE, -1);
//            if (type != 1) {
//                clear.setVisibility(View.VISIBLE);
//            }
            if (type == 1) {
                url = intent.getStringExtra(EX_URL);
            } else if (type == 2) {
                url = ColumnBaseFragment.getSubscribeUrl();
                if (TextUtils.isEmpty(url)) {
                    url = (String) SharedPreferencesUtil.getParam(this, Constances.SUBSCRIBE_KEY, "");
                }
            }
            getNetSubscribeList(url, currentPage);
        }
    }

    private void setDates(FSubscribe subscribe) {
        month = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "MM");
        day = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "dd");
        hour = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "HH");
        minute = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "mm");
        if (month.substring(0, 1).equals("0")) {
            month = month.substring(1, 2);
        }
        if (day.substring(0, 1).equals("0")) {
            day = day.substring(1, 2);
        }
        if (hour.substring(0, 1).equals("0")) {
            hour = hour.substring(1, 2);
        }
        if (minute.substring(0, 1).equals("0")) {
            minute = minute.substring(1, 2);
        }
    }

    /**
     * 匹配可预约的直播以及用户已预约的直播
     *
     * @param list
     */
    private void initInfo(List<FSubscribe> list) {
        // list.get(0).setLiveTime("2017-09-23 17:03:00");
        List<FSubscribe> dbListData = getDbListData();
        if (ListUtils.isListValued(dbListData)) {
            for (int i = 0; i < list.size(); i++) {
                if (!getCurentTime(list.get(i))) {
                    list.remove(list.get(i));
                    i--;
                    continue;
                }
                String liveId = list.get(i).getLiveId();
                for (FSubscribe subscribe : dbListData) {
                    if (liveId.equals(subscribe.getLiveId())) {
                        list.get(i).setSubscribe(subscribe.isSubscribe());
                        readySubscribe.add(list.get(i));  //本地数据与数据库数据进行匹配
                    }
                }
            }
        }
        if (type == 1) {
            for (int i = 0; i < list.size(); i++) {
                if (!getCurentTime(list.get(i))) {
                    list.remove(list.get(i));
                    i--;
                }
            }
            subscribeList = list;
        } else {
            subscribeList = readySubscribe;
            if (ListUtils.isListValued(readySubscribe)) {
                no_subscribe.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
            } else {
                no_subscribe.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }
        }
        if (currentPage == 0) {
            if (adapter == null) {
                adapter = new MySubscribeAdapter(MySubscribeActivity.this, subscribeList).setItemInternalClick(mySubscribeClick);
                subscribe_rv.setAdapter(adapter);
            } else {
                adapter.setData(subscribeList);
            }
        } else {
            adapter.addDatas(subscribeList);
        }

    }

    private OnItemInternalClick mySubscribeClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FSubscribe subscribe = null;
            if (view == null) {
                subscribe = (FSubscribe) itemView.getTag(R.id.adapter_item_data_key);
            } else {
                subscribe = (FSubscribe) itemView.getTag(R.id.adapter_item_data_key);
            }
            if (type != 1) {
                adapter.remove(position);
                deleteSubscribe(subscribe);
                stopAlarm(subscribe.getLiveId(), subscribe.getLiveTitle(), subscribe.getLiveUrl());

            } else {
                if (subscribe.isSubscribe()) {
                    stopAlarm(subscribe.getLiveId(), subscribe.getLiveTitle(), subscribe.getLiveUrl());
                    subscribe.setSubscribe(!subscribe.isSubscribe());
                    adapter.notifyDataSetChanged();
                    deleteSubscribe(subscribe);
                } else {
                    if(NotificationsUtils.isNotificationEnabled(MySubscribeActivity.this) ){
                        if (!TextUtils.isEmpty(subscribe.getLiveUrl()) && !TextUtils.isEmpty(subscribe.getLiveTime())) {
                            setAlarm(subscribe.getLiveId(), subscribe.getLiveTitle(), subscribe.getLiveUrl(), subscribe);
                        } else {
                            toast("直播地址或者预约时间为空不能进行预约");
                        }
                    }else{
                        showDialog();
                    }

                }
            }
        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void setSubscribeList(FSubscribe subscribe) {
        DBUtils.getInstance().replaceAxync(subscribe);
    }

    /**
     * 删除预约
     *
     * @param fSubscribe
     */
    private void deleteSubscribe(FSubscribe fSubscribe) {
        try {
            DBUtils.getInstance().getDbManager().deleteById(FSubscribe.class, fSubscribe.getLiveId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取可预约的直播数据
     *
     * @param url
     * @param calledPage
     */
    private synchronized void getNetSubscribeList(String url, int calledPage) {
        if (TextUtils.isEmpty(url)) {
            if (type == 2) {
                no_subscribe.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }
//            if (type == 1) {
//                toast("数据错误");
//            }
            if (refreshLayout.isRefreshing()) {
                refreshLayout.refreshComplete();
            }
            return;
        }
        no_subscribe.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
        NetUtils.getNetAdapter().getSubscribeListPage(getOwnerName(), url, calledPage, new AbsListNetCallback<FSubscribe>(ListTypeUtils.FSubscribe(), calledPage) {
            @Override
            public void onSuc(List<FSubscribe> fSubscribes) {
                if (ListUtils.isListValued(fSubscribes)) {
                    currentPage = getPageResponse().getData().getPageIndex();
                    pageAll = getPageResponse().getData().getPageAll();
                    initInfo(fSubscribes);
                } else {
                    no_subscribe.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });

    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
    }

    /**
     * 获取本地已预约的直播数据
     *
     * @return
     */
    private List<FSubscribe> getDbListData() {
        try {
            List<FSubscribe> list = DBUtils.getInstance().findAll(FSubscribe.class);
            if (ListUtils.isListValued(list)) {
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean getCurentTime(FSubscribe fSubscribe) {
        if (calendar == null) {
            calendar = Calendar.getInstance();
        }
        long timeInMillis = calendar.getTimeInMillis();
        Date dataDate = DateUtils.getDataDate(fSubscribe);
        if (dataDate != null) {
            long liveTime = dataDate.getTime();
            if (timeInMillis <= liveTime) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == ShowDiaFragment.NOTIFICATION_TAG) {
                toSetting();
            }
        }
    };


}
